package com.zz.interceptor;

import com.zz.dto.LoginToken;
import com.zz.util.Constants;
import com.zz.util.VideoUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
@Component
public class AutoLoginInterceptor  extends HandlerInterceptorAdapter {
    /**
     * 做自动登录的验证,如果cookie里面的token能够通过验证
     * 就直接做登录,把application里面的user存到session里
     * */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String CookieTokenValue = VideoUtil.getCookieTokenValue(request.getCookies());
        Boolean  valid =  VideoUtil.checkLoginToken(CookieTokenValue,request);
        System.out.println("拦截器valid: "+valid);
        if (valid){
            ServletContext application =  request.getServletContext();
            HashMap<String, LoginToken> tokenHashMap = (HashMap<String, LoginToken>) application.getAttribute(Constants.AUTO_LOGIN_TOKEN);
            LoginToken loginToken = tokenHashMap.get(CookieTokenValue);
            request.getSession().setAttribute(Constants.SESSION_LOGIN_USER,loginToken);
        }
        return true ;
    }
}
